<template>
  <div class="search">
    <el-card shadow="hover" class="search-view">
      <template #header>
        <h4>关键词搜索</h4>
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-icon class="el-icon--right">
              <MoreFilled />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>Action1</el-dropdown-item>
              <el-dropdown-item>Action2</el-dropdown-item>
              <el-dropdown-item>Action3</el-dropdown-item>
              <el-dropdown-item disabled>Action4</el-dropdown-item>
              <el-dropdown-item divided>Action5</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
      <div class="search-wrap">
        <div class="search-wrap-chart">
          <div class="chart-title">搜索用户数</div>
          <div class="chart-value">
            {{ numberFormater(lineChartData.totalUser) }}
          </div>
          <v-chart
            :option="getLineOption('userList', '搜索用户数')"
            autoresize
          ></v-chart>
        </div>
        <div class="search-wrap-chart">
          <div class="chart-title">总的搜索量</div>
          <div class="chart-value">
            {{ numberFormater(lineChartData.totalCount) }}
          </div>
          <v-chart
            :option="getLineOption('countList', '总的搜索量')"
            autoresize
          ></v-chart>
        </div>
      </div>
      <el-table :data="tabledata">
        <el-table-column label="排名" prop="rankNo"></el-table-column>
        <el-table-column label="关键词" prop="word"></el-table-column>
        <el-table-column label="搜索数量" prop="count"></el-table-column>
        <el-table-column label="搜索用户数" prop="user"></el-table-column>
        <el-table-column label="搜索占比" prop="range"></el-table-column>
      </el-table>
      <el-pagination
        layout="prev,pager,next"
        :total="tableTotalData.length"
        v-model:current-page="currentPage"
        :page-size="pageSize"
      ></el-pagination>
    </el-card>
    <el-card shadow="hover" class="search-view">
      <!-- shadow设置卡片阴影出现的时机 -->
      <template #header>
        <h4>分类销售排行</h4>
        <el-radio-group>
          <el-radio-button label="品类">品类</el-radio-button>
          <el-radio-button label="商品">商品</el-radio-button>
        </el-radio-group>
      </template>
      <div class="pie-chart">
        <v-chart :option="getPieOption()" autoresize></v-chart>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Search",
});
</script>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { MoreFilled } from "@element-plus/icons-vue";
import { useReportDataStore } from "@/stores/reportData";
import useFormater from "@/hooks/useFormater";

const { numberFormater, moneyFormater } = useFormater();
const reportInfoStore = useReportDataStore();
const tabPosition = ref("品类");
const currentPage = ref(1);
const pageSize = ref(5);

//准备左侧数据
const searchWord = computed(() => reportInfoStore.reportData.searchWord);

//准备底部右侧数据
const saleRank = computed(() => reportInfoStore.reportData.saleRank);

//列表数据
const tableTotalData = computed(() => {
  if (!searchWord.value) return [];
  return searchWord.value.map((item, index) => ({
    ...item,
    rankNo: index + 1,
    range: ((item.user / item.count) * 100).toFixed(2) + "%",
  }));
});

const tabledata = computed(() => {
  return tableTotalData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
});

//从tableTotalData中准备一些渲染需要的数据 X轴 Y轴

const lineChartData = computed(() => {
  const data = {
    wordList: [] as string[], //折线图x轴需要用到的数据 两个图公用这个数据就行
    countList: [] as number[], //搜索用户数，其实就是折线图Y轴会用到的数据
    userList: [] as number[], //搜索量数据 其实就是搜索量折线图
    totalUser: 0, //搜索用户数总量统计
    totalCount: 0, //总的搜索量统计
  };
  tableTotalData.value.forEach((item: any) => {
    data.wordList.push(item.word);
    data.countList.push(item.count);
    data.userList.push(item.user);
    data.totalUser += item.user;
    data.totalCount += item.count;
  });
  return data;
});
const getLineOption = (listName: "userList" | "countList", name: string) => {
  return {
    xAxis: {
      boundaryGap: false, //两侧不留白
      data: lineChartData.value.wordList,
    },
    yAxis: {
      show: false,
    },
    tooltip: {
      trigger: "axis", //只有鼠标在x轴就会触发
      confine: true, //显示的内容实在图形内 false 则在外面
    },
    grid: {
      left: 0,
      top: 0,
      right: 0,
      bottom: 0,
    },
    series: {
      type: "line",
      smooth: true, //次属性可让折线更平滑
      itemStyle: {
        //折线点 不要显示
        opacity: 0,
      },
      lineStyle: {
        color: "#5FBBFF",
      },
      areaStyle: {
        //折线图区域内的颜色
        color: "#C7E7FF",
      },
      data: lineChartData.value[listName],
    },
  };
};
//准备饼状图数据
const pieChartData = computed(() => {
  const data = {
    categoryList: [] as any, //品类的数组
    goodsList: [] as any, //商品的数组
    cTotal: 0, //品类的总数组
    gTotal: 0, //商品的总数组
  };
  console.log(saleRank.value,1111);
  
  if (!saleRank.value) return {} as any; //这样如果是true就不会继续往下走
  const {
    category: { axisX, data1 },
    goods: { axisX: axisX2, data1: data2 }, //两组数组名字相同所以结构的时候要取别名 否则会报错
  } = saleRank.value;
  

  const total1 = data1.reduce((prev, item) => prev + item, 0);
  data.cTotal = total1;

  const total2 = data2.reduce((prev, item) => prev + item, 0);
  data.gTotal = total2;

  axisX.forEach((item, index) => {
    const percent = ((data1[index] / total1) * 100).toFixed(2) + "%";
    data.categoryList.push({
      name: item + "|" + percent,
      labelName: item,
      value: data1[index],
      percent,
    });
  });
  axisX2.forEach((item, index) => {
    const percent = ((data2[index] / total2) * 100).toFixed(2) + "%";
    data.goodsList.push({
      name: item + "|" + percent,
      labelName: item,
      value: data2[index],
      percent,
    });
  });
  return data;
});

//准备饼状图渲染时的参数
console.log(pieChartData.value,222);

const getPieOption = () => {
  const list =
    tabPosition.value === "品类"
      ? pieChartData.value.categoryList
      : pieChartData.value.goodsList;
  const text = tabPosition.value === "品类" ? "品类分布" : "商品分布";
  const subtext =
    tabPosition.value === "品类"
      ? pieChartData.value.cTotal
      : pieChartData.value.gTotal;
  return {
    title: [
      {
        text,
        textStyle: {
          fontSize: 14,
          color: "#666",
        },
        left: 20,
        top: 20,
      },
      {
        text: "累计订单量",
        textStyle: {
          fontSize: 14,
          color: "#999",
        },
        subtext,
        subtextStyle: {
          fontSize: 36,
          color: "#333",
        },
        left: "34.5%",
        top: "42.5%",
        textAlign: "center",
      },
    ],
    tooltip: {
      trigger: "item",
      formatter: (params: any) => {
        return `${tabPosition.value}分布<br/>
          ${params.marker + params.data.labelName}<br/>
          ${params.marker}数量:${params.data.value}<br/>
          ${params.marker}占比:${params.data.percent}<br/>
        `;
      },
    },
    legend: {
      orient: "vertical",
      top: "middle",
      left: "70%",
      textStyle: {
        color: "#8c8c8c",
      },
    },
    series: [
      {
        name: "Access From",
        type: "pie",
        radius: ["39%", "57%"],
        center: ["35%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          // borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          position: "outside",
          formatter: function (params: any) {
            // console.log(params);
            return params.data.labelName;
          },
        },
        // emphasis: {
        //   label: {
        //     show: true,
        //     fontSize: 40,
        //     fontWeight: 'bold'
        //   }
        // },
        // 视频引导线的设置
        labelLine: {
          // show: true
          length: 7,
          length2: 5,
        },
        // data: [
        //   { value: 1048, name: 'Search Engine' },
        //   { value: 735, name: 'Direct' },
        //   { value: 580, name: 'Email' },
        //   { value: 484, name: 'Union Ads' },
        //   { value: 300, name: 'Video Ads' }
        // ]
        data: list,
      },
    ],
  };
};
</script>



<style lang="scss" scoped>
.search {
  display: flex;
  .search-view {
    flex: 1;
    cursor: pointer;
    &:first-child {
      margin-right: 10px;
      .search-wrap {
        .search-wrap-chart {
          display: inline-block;
          width: 50%;
          &:first-child {
            padding-right: 10px;
          }
          .chart-title {
            font-size: 14px;
            color: #999;
          }
          .chart-value {
            font-size: 24px;
            line-height: 26px;
            letter-spacing: 1px;
          }
          .echarts {
            height: 50px;
          }
        }
      }
    }
    &:last-child {
      margin-left: 10px;
      .pie-chart {
        height: 400px;
      }
    }
    :deep(.el-card__header) {
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      h4 {
        font-size: 16px;
        font-weight: 600;
      }
    }
  }
}
</style>